package com.ljx.NoteBody.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.ljx.NoteBody.common.MyException;
import com.ljx.NoteBody.entity.Agree;
import com.ljx.NoteBody.mapper.AgreeMapper;
import com.ljx.NoteBody.mapper.CommentsMapper;
import com.ljx.NoteBody.service.AgreeService;
import com.ljx.NoteBody.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
public class AgreeServiceImpl implements AgreeService {

    @Autowired
    AgreeMapper agreeMapper;

    @Autowired
    CommentsMapper commentsMapper;

    @Transactional
    @Override
    public void changAgree(Long commentId, HttpServletRequest request) {
        LocalDateTime time = LocalDateTime.now();
        DecodedJWT token = TokenUtil.verify(request.getHeader("token"));;
        String username = token.getClaim("username").asString();
        // 查找用户是否已经有过点赞记录
        int i  = 0;
        try{
            Agree agree = agreeMapper.queryAgree(username, commentId);
            agree.setUpdateTime(time);
            if(agree.getAgree() == 0) {
                // 评论点赞加1
                i = commentsMapper.commentAgreeAdd(commentId);
                if(i <= 0) throw new MyException("点赞加一出错");
                agree.setAgree(1);
            }
            else {
                // 评论点赞减1
                i = commentsMapper.commentAgreeSub(commentId);
                if(i <= 0) throw new MyException("点赞加一出错");
                agree.setAgree(0);
            }
            i = agreeMapper.updateAgree(agree);
            if(i <= 0) throw new MyException("更新点赞出错");
        } catch (Exception e){
            Agree agree = new Agree();
            agree.setCommentId(commentId);
            agree.setCreateTime(time);
            agree.setUsername(username);
            agree.setUpdateTime(time);
            agree.setAgree(1);
            i = commentsMapper.commentAgreeAdd(commentId);
            if(i <= 0) throw new MyException("点赞加一出错");
            i = agreeMapper.saveAgree(agree);
            if(i <= 0) throw new MyException("点赞保存出错");
        }
    }
}
